package com.cn.transfer.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.InspectionData;
import com.cn.transfer.common.entity.jiandaoyun.Order0111;
import com.cn.transfer.common.entity.jiandaoyun.SalesCalculation;
import com.cn.transfer.common.entity.jiandaoyun.SalesOrderKu;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author: weidian
 * @date: 2024/7/29 09:27
 * @Description: 销售订单金额计算
 */
@RestController
@Slf4j
public class SalesOrderCalculation {
    private final ResourceLoader resourceLoader;

    private static final String SECRET = "ERsdfSFWERDSFDSd";
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    public SalesOrderCalculation(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private static final int CORE_POOL_SIZE = 20;         // 核心线程数
    private static final int MAXIMUM_POOL_SIZE = 50;     // 最大线程数
    private static final long KEEP_ALIVE_TIME = 60L;      // 空闲线程存活时间
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // 存活时间单位
    private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(150); // 任务队列

    // 创建自定义线程池
    private static ExecutorService threadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TIME_UNIT,
            WORK_QUEUE,
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
    );

    @PostMapping("/SalesOrderCalculation")
    public String callback(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        //log.info("存货申请=====" + payload);
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        threadPool.submit(() -> handleData(payload));

        return "success";
    }
    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, SalesOrderCalculation.SECRET, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String secret, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + secret + ":" + timestamp);
    }
    private void handleData(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_UPDATE.equals(op)) {
            uodate(data,true);
        }else if (DATA_DELETE.equals(op)) {
            uodate(data,false);
        }
    }
    private void uodate(String data,boolean fale) {
        Header[] headers = ConnmeUtils.createHeaders();
        SalesCalculation salesCalculation = JSONUtil.toBean(data, SalesCalculation.class);

        if (fale){
            if (salesCalculation.getFlowState()!=1){
                return;
            }
        }

        Map<String, Map<String,Double>> yushou = new HashMap<>();
        Map<String,  Map<String,Double>> weikuan = new HashMap<>();


        for (SalesCalculation.OrderPrepayment orderPrepayment : salesCalculation.get_widget_1721546510495()) {
            if (yushou.containsKey(orderPrepayment.get_widget_1721546510504())){
                Map<String, Double> stringDoubleMap = yushou.get(orderPrepayment.get_widget_1721546510504());
                if (stringDoubleMap.containsKey(orderPrepayment.get_widget_1721616942683())){
                    Double aDouble = yushou.get(orderPrepayment.get_widget_1721546510504()).get(orderPrepayment.get_widget_1721616942683());
                    stringDoubleMap.put(orderPrepayment.get_widget_1721616942683(),orderPrepayment.get_widget_1721546510520()+aDouble);
                }else {
                    stringDoubleMap.put(orderPrepayment.get_widget_1721616942683(),orderPrepayment.get_widget_1721546510520());
                }

            }else {
                Map<String,Double> yushou001 = new HashMap<>();
                yushou001.put(orderPrepayment.get_widget_1721616942683(),orderPrepayment.get_widget_1721546510520());
                yushou.put(orderPrepayment.get_widget_1721546510504(),yushou001);
            }
        }

        chuliYuSuan(headers, yushou,true,fale);


        for (SalesCalculation.OrderFinalPayment orderFinalPayment : salesCalculation.get_widget_1721548605263()) {
            if (weikuan.containsKey(orderFinalPayment.get_widget_1721548605264())){
                Map<String, Double> stringDoubleMap = weikuan.get(orderFinalPayment.get_widget_1721548605264());
                if (stringDoubleMap.containsKey(orderFinalPayment.get_widget_1721616942684())){
                    Double aDouble = weikuan.get(orderFinalPayment.get_widget_1721548605264()).get(orderFinalPayment.get_widget_1721616942684());
                    stringDoubleMap.put(orderFinalPayment.get_widget_1721616942684(),orderFinalPayment.get_widget_1721548605266()+aDouble);
                }else {
                    stringDoubleMap.put(orderFinalPayment.get_widget_1721616942684(),orderFinalPayment.get_widget_1721548605266());
                }

            }else {
                Map<String,Double> yushou001 = new HashMap<>();
                yushou001.put(orderFinalPayment.get_widget_1721616942684(),orderFinalPayment.get_widget_1721548605266());
                weikuan.put(orderFinalPayment.get_widget_1721548605264(),yushou001);
            }
        }

        chuliYuSuan(headers, weikuan,false,fale);

    }

    private void chuliYuSuan(Header[] headers, Map<String, Map<String, Double>> weikuan,boolean ister,boolean fale) {
        weikuan.forEach((key, innerMap) -> {
            try {
                Map<String, Object> parameterCx = new HashMap<>();
                parameterCx.put("app_id", "667230ad22a8581756b77d52");
                parameterCx.put("entry_id", "669e17aa09cd4f4e279d4d5d");
                log.info("Querying based on key: " + key);
                List<SalesOrderKu> salesOrderKus = PurchaseCommunity.queryBased(parameterCx, headers, key, "_widget_1718759603973", SalesOrderKu.class);

                if (salesOrderKus == null || salesOrderKus.isEmpty()) {
                    log.warn("No sales order data found for key: " + key);
                    return; // 继续下一个key
                }

                log.info("Processing innerMap: " + innerMap);
                innerMap.forEach((innerKey, value) -> {
                    log.info("Processing inner key: " + innerKey + ", value: " + value);
                    SalesOrderKu salesOrderKu = salesOrderKus.get(0);
                    if (salesOrderKu == null) {
                        log.error("SalesOrderKu is null for key: " + key);
                        return;
                    }

                    List<SalesOrderKu.OrderDetail> orderDetails = salesOrderKu.get_widget_1718759603981();
                    if (orderDetails == null) {
                        log.error("Order details are null for SalesOrderKu: " + salesOrderKu);
                        return;
                    }

                    for (SalesOrderKu.OrderDetail orderDetail : orderDetails) {
                        if (orderDetail == null) {
                            log.error("Order detail is null in order details list.");
                            continue;
                        }

                        if (orderDetail.get_widget_1718759603995() == null) {
                            log.error("Order detail inner key is null for order detail: " + orderDetail);
                            continue;
                        }

                        if (orderDetail.get_widget_1718759603995().equals(innerKey)) {
                            if (ister) {
                                if (fale){
                                    if (orderDetail.get_widget_1721982279364() == null) {
                                        orderDetail.set_widget_1721982279364(value);
                                    } else {
                                        orderDetail.set_widget_1721982279364(value + orderDetail.get_widget_1721982279364());
                                    }
                                }else {
                                    if (orderDetail.get_widget_1721982279364() == null) {
                                       log.info("累计预收为空，无法计算");
                                    } else {
                                        orderDetail.set_widget_1721982279364(value - orderDetail.get_widget_1721982279364());
                                    }
                                }

                            } else {
                                if (fale){
                                    if (orderDetail.get_widget_1721982279365() == null) {
                                        orderDetail.set_widget_1721982279365(value);
                                    } else {
                                        orderDetail.set_widget_1721982279365(value + orderDetail.get_widget_1721982279365());
                                    }
                                }else {
                                    if (orderDetail.get_widget_1721982279365() == null) {
                                        log.info("累计尾款为空，无法计算");
                                    } else {
                                        orderDetail.set_widget_1721982279365(value - orderDetail.get_widget_1721982279365());
                                    }
                                }

                            }
                            if (orderDetail.get_widget_1721982279365() != null && orderDetail.get_widget_1721982279364() != null){
                                orderDetail.set_widget_1722241817628(orderDetail.get_widget_1721639369902()-orderDetail
                                        .get_widget_1721982279365()-orderDetail.get_widget_1721982279364());
                            }
                            log.info("Updated order detail: " + orderDetail);
                        }
                    }
                });

                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "667230ad22a8581756b77d52");
                parameterInster.put("entry_id", "669e17aa09cd4f4e279d4d5d");
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", salesOrderKus.get(0).get_id());
                salesOrderKus.get(0).set_id(null);
                salesOrderKus.get(0).set_widget_1718759603978(null);
                salesOrderKus.get(0).set_widget_1718759603990(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(salesOrderKus.get(0)));
                String jsonSale = JSONUtil.toJsonStr(parameterInster);
                log.info("Modified sales order prepayment: " + jsonSale);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
            } catch (Exception e) {
                log.error("Error processing key: " + key, e);
            }
        });


    }
}
